package com.bsuir.avareader.logic;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.os.Environment;

public class FileManager {
	private File currentDirectory = Environment.getExternalStorageDirectory();
	private int mStepBack = 0;

	public List<String> getDir() {
		List<String> items = new ArrayList<String>();
		String sFile[] = currentDirectory.list(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return ((name.endsWith(".fb2")) || (name.endsWith(".html")) || (name
						.endsWith(".txt")));
			}
		});
		String sDir[] = currentDirectory.list(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return (new File(dir, name).isDirectory());
			}
		});
		items.clear();
		Arrays.sort(sFile, String.CASE_INSENSITIVE_ORDER);
		Arrays.sort(sDir, String.CASE_INSENSITIVE_ORDER);
		items.addAll(Arrays.asList(sDir));
		items.addAll(Arrays.asList(sFile));
		return items;
	}

	public List<String> upOneLevel() {
		if (mStepBack != 0) {
			currentDirectory = currentDirectory.getParentFile();
			mStepBack--;
			return getDir();
		}
		return null;
	}

	public static boolean isSDCardMounted() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	public void setCurrentDirectory(String item) {
		currentDirectory = new File(currentDirectory.getAbsolutePath() + "/"
				+ item + "/");
		mStepBack++;
	}

	public boolean itemIsDirectory(String item) {
		return (new File(currentDirectory.getAbsolutePath() + "/" + item + "/")
				.isDirectory());
	}

	public File getFile(String item) {
		return (new File(currentDirectory.getAbsolutePath() + "/" + item + "/"));
	}

}
